package servidor;

import java.net.SocketException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.util.logging.Level;
import java.util.logging.Logger;
import implementaciones.interfazServidorImpl;
import interfaz.interfazServidor;
import java.io.*;
import java.lang.Thread;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import util.funcionesServerRE;
import java.util.*;

public class vistaServidor extends javax.swing.JFrame {
    //Se instancia la clase conexion para poder iniciar una,
    //o eventualmente detenerla

    private conexionRE conexion = new conexionRE();
    public hiloConsultaRut hilo;
    public boolean continuo=true;
    public interfazServidorImpl objeto;

    public vistaServidor() {
        initComponents();
        hiloConsultaRut hilo = new hiloConsultaRut();
            hilo.start();
            
     

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jButtonFinalizarVotacionPrimaria = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jComboBoxPartido = new javax.swing.JComboBox();
        jComboBoxComuna = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        ButtonIniciar = new javax.swing.JButton();
        ButtonDetener = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Servidor Registro Electoral");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setName("Finalizar votaciones Primarias"); // NOI18N

        jButtonFinalizarVotacionPrimaria.setText("Finalizar votacion");
        jButtonFinalizarVotacionPrimaria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFinalizarVotacionPrimariaActionPerformed(evt);
            }
        });

        jLabel1.setText("Partido");

        jLabel2.setText("Comuna");

        jComboBoxPartido.addItem("DC");
        jComboBoxPartido.addItem("PC");
        jComboBoxPartido.addItem("UDI");

        jComboBoxComuna.addItem("Heterogeneidad");
        jComboBoxComuna.addItem("Transparencia");
        jComboBoxComuna.addItem("Escalabilidad");
        jComboBoxComuna.addItem("Concurrencia");
        jComboBoxComuna.addItem("Adaptabilidad");

        jLabel3.setText("Finalizar Votaciones Primarias");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(26, 26, 26)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jComboBoxPartido, 0, 167, Short.MAX_VALUE)
                            .addComponent(jComboBoxComuna, 0, 167, Short.MAX_VALUE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(48, 48, 48)
                        .addComponent(jButtonFinalizarVotacionPrimaria, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                        .addGap(35, 35, 35)))
                .addContainerGap())
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(115, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jComboBoxPartido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jComboBoxComuna, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonFinalizarVotacionPrimaria)
                .addContainerGap())
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        ButtonIniciar.setText("Iniciar Sever");
        ButtonIniciar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                iniciarServer(evt);
            }
        });

        ButtonDetener.setText("Detener Server");
        ButtonDetener.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                detenerServer(evt);
            }
        });

        jLabel4.setText("Iniciar/Detener Server");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(51, 51, 51)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ButtonDetener, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                    .addComponent(ButtonIniciar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel4)
                .addContainerGap(163, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addComponent(ButtonIniciar)
                .addGap(18, 18, 18)
                .addComponent(ButtonDetener)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(46, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void iniciarServer(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_iniciarServer
        Registry registro;

        try {
            registro = conexion.getRegistry();
            //Se instancia el objeto que implementa la interfaz del Servidor
            //Ahora hay que hacerlo remoto, para ello se registra en el Registry
            //con el método "rebind" que lo registra con un nombre para poder ser visto en ese espacio
            //en este caso se le dio el nombre "Implementacion".
            //interfazServidorImpl objeto = new interfazServidorImpl();
            objeto = new interfazServidorImpl();
            registro.rebind("Implementacion", objeto);
            objeto.cargarRegistrados();
            this.ButtonIniciar.setEnabled(false);
            
    

        } catch (RemoteException ex) {
            Logger.getLogger(vistaServidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_iniciarServer

    private void detenerServer(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_detenerServer
        try {
         
            conexion.detener();
            this.ButtonIniciar.setEnabled(true);
        } catch (RemoteException ex) {
            Logger.getLogger(vistaServidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_detenerServer

    private void jButtonFinalizarVotacionPrimariaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFinalizarVotacionPrimariaActionPerformed

        objeto.finalizarVotacionPrimaria(this.jComboBoxPartido.getSelectedItem().toString(),
                this.jComboBoxComuna.getSelectedItem().toString());
        
    }//GEN-LAST:event_jButtonFinalizarVotacionPrimariaActionPerformed

    public class hiloConsultaRut extends Thread {
     
        private DatagramSocket socket;
        private Socket s;
        private ServerSocket ss;
        private funcionesServerRE helper= new funcionesServerRE();
        String msje_enviado=null;
        public void run() {
            while (continuo) {

                try {
                    System.out.println("A la escucha");
                    ss = new ServerSocket(10000);
                    s = ss.accept();
                    System.out.println("Client Accepted");
                    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    String[] contenido= br.readLine().split(",");
                    if(contenido.length==2){
                    System.out.println(contenido[0]);
                    System.out.println(contenido[1]);
                    
                    if(contenido[0].equals("validar")){
                    String rut= contenido[1];
                    //Esta es la funcion comprueba cualquier tipo de ingreso para Rut y para el campo si/no
                    msje_enviado= helper.comprobarInscritos(rut);
                    }
                    }
                            
                    else{
                    msje_enviado="Error de formato";
                    }
                    
                    //Envío mensaje
                    PrintWriter wr = new PrintWriter(new OutputStreamWriter(s.getOutputStream()), true);
                    wr.println(msje_enviado);

                    ss.close();
                    s.close();
                } catch (Exception e) {
                    System.out.println(e);
                    

                }

            }
            System.out.println("Termine de oir");
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonDetener;
    private javax.swing.JButton ButtonIniciar;
    private javax.swing.JButton jButtonFinalizarVotacionPrimaria;
    private javax.swing.JComboBox jComboBoxComuna;
    private javax.swing.JComboBox jComboBoxPartido;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
}
